package com.netnovelstore.interceptor;

import com.netnovelstore.config.JwtUtil;
import com.netnovelstore.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // http 的 header 中获得token
        String token = request.getHeader("authorization");

        // token 不存在
        if (token == null || token.equals("")) {
            log.error("UserLoginInterceptor class token is not exist");
            response.sendError(401,"拒绝访问 : 无身份");
            return false;
        }
        //管理员用
        if (token.equals(JwtUtil.secret))
            return true;
        // 验证 token
        String sub = JwtUtil.validateToken(token);
        if (sub == null || sub.equals("")) {
            log.warn("token exist, but not same");

            response.sendError(403,"拒绝访问 : 身份错误");
            return false;
        }
        if (!redisUtil.exists(token)) {
            log.warn("token error");
            response.sendError(403,"拒绝访问 : 身份已过期");
            return false;
        }
        // 更新 token 有效时间 (如果需要更新其实就是产生一个新的 token)
        if (JwtUtil.isNeedUpdate(token)) {
            String newToken = JwtUtil.createToken(sub);
            response.setHeader(JwtUtil.USER_LOGIN_TOKEN, newToken);
        }
        return true;
    }

}
